package com.jtyoui.controller;

import com.jtyoui.model.InMessage;
import com.jtyoui.model.User;
import com.jtyoui.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ChatController {

    @Autowired
    private WebSocketService webSocketService;

    private static Map<String, String> userMap = new HashMap<>();
    public static Map<String, User> onlineUser = new HashMap<>();

    static {
        userMap.put("jack", "123");
        userMap.put("mary", "456");
        userMap.put("tom", "789");
        userMap.put("tim", "000");
        userMap.put("小D", "666");
        onlineUser.put("123", new User("我的电脑", "888"));
    }

    @Scheduled(fixedRate = 2000)
    public void onlineUser() {
        webSocketService.sendOnlineUser(onlineUser);
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String userLogin(String username, String pwd, HttpSession session) {
        String password = userMap.get(username);
        if (pwd.equals(password)) {
            User user = new User(username, pwd);
            String sessionId = session.getId();
            onlineUser.put(sessionId, user);
            return "redirect:/html/qq.html";
        } else {
//            return "redirect:/error.html";
            return null;
        }
    }

    @MessageMapping("/chat")
    public void topicChat(InMessage message, SimpMessageHeaderAccessor headerAccessor) {
        String sessionId = headerAccessor.getSessionAttributes().get("sessionId").toString();
        User user = onlineUser.get(sessionId);
        message.setFrom(user.getUsername());
        webSocketService.sendTopicChat(message);
    }

}
